package net.plentz.tagger.data.access;

import java.io.File;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.ImageIcon;
import javax.swing.filechooser.FileSystemView;

import net.plentz.tagger.Util;

import org.eclipse.swt.graphics.ImageData;

public class FileDAO {

	private static final String[] FileSizes = new String[] {
			"B", "KB", "MB", "GB", "TB", "PB"
	};
	public static final Map<String, ImageData> SystemIconCache = new HashMap<String, ImageData>();

	public static String formatFileSize(long size) {
		int index = 0;
		while (size > 1024) {
			index += 1;
			size /= 1024;
		}
		return size + FileDAO.FileSizes[index];
	}

	public static List<File> getFiles(File directory) {
		return FileDAO.getFiles(directory, true, new String[0]);
	}

	public static List<File> getFiles(File directory, boolean includeDirectories, String[] extensions) {

		if (!directory.isDirectory()) {
			throw new RuntimeException("Directory [" + directory + "] is not a valid directory");
		}

		List<File> result = new ArrayList<File>();
		String[] filenames = directory.list();
		boolean hasExtensionRestriction = extensions.length > 0;

		for (int i = 0, il = extensions.length; i < il; i++) {
			if (!extensions[i].startsWith(".")) {
				extensions[i] = "." + extensions[i];
			}
		}

		int directoryIndex = 0;

		if (filenames != null) {
			for (String filename : filenames) {
				File file = new File(directory.getAbsolutePath() + "/" + filename);
				if (hasExtensionRestriction && !(includeDirectories && file.isDirectory())) {
					boolean passes = false;
					for (String extension : extensions) {
						if (filename.endsWith(extension)) {
							passes = true;
							break;
						}
					}
					if (!passes) {
						continue;
					}
				}
				if (!file.isDirectory() || includeDirectories) {
					if (file.isDirectory()) {
						result.add(directoryIndex++, file);
					} else {
						result.add(file);
					}
				}
			}
		}

		return result;

	}

	public static ImageData getSystemIconForFile(File file) throws NoSuchAlgorithmException {
		FileSystemView fileSystemView = FileSystemView.getFileSystemView();
		ImageIcon icon = (ImageIcon)fileSystemView.getSystemIcon(file);
		ImageData data = Util.convertAWTImageToSWT(icon.getImage());
		String key = Util.getMD5(data.data);
		if (FileDAO.SystemIconCache.get(key) == null) {
			FileDAO.SystemIconCache.put(key, data);
		}
		return FileDAO.SystemIconCache.get(key);
	}

}
